<template>
  <div class="dialogue">
    <header id="wx-header">
      <!-- 顶部导航栏 右侧按钮 -->
      <div class="other">
        <!-- 前往群详情 -->
        <router-link
          :to="{
            path: '/wechat/dialogue/dialogue-info',
            query: { mid: mid },
          }"
          tag="span"
          class="iconfont icon-chat-group"
          v-if="midInfo.type == 2"
        >
        </router-link>
        <!-- 前往个人详情 -->
        <router-link
          :to="{
            path: '/wechat/dialogue/dialogue-detail',
            query: { mid: mid },
          }"
          tag="span"
          class="iconfont icon-chat-friends"
          v-if="midInfo.type == 1"
        ></router-link>
      </div>

      <!-- 顶部导航栏标题 -->
      <div class="center">
        <!-- <router-link to="" tag="div"> -->
        <div @click="returnBtn" class="iconfont icon-return-arrow">
          <van-badge class="van-badge" v-if="msgNumberAll>0" :content="msgNumberAll" max="99"/>
        </div>

        <!-- </router-link> -->
        <div class="dialogue-title-box">
          {{ midNickName
          }}<span class="parentheses" v-if="midInfo.type == 2">{{
            midNumber
          }}</span>
          <span v-if="midInfo.type == 1 && midInfo.online == 1" class="cgreen"
            >[在线]</span
          >
        </div>
      </div>
    </header>

    <!-- 长按菜单事件 -->
    <section
      class="dialogue-section"
      id="msg-list"
      v-on:click="MenuOutsideClick"
    >
      <div class="system-msg" v-if="finished">没有更多了</div>
      <div class="system-msg" v-if="loading">加载中...</div>
      <!-- 消息列表 -->
      <div v-for="(item, index) in msgList.list" :key="'key_'+index">

        <!-- 时间提示 -->
        <div class="system-msg" v-if="item.showTime==1 && item.datetime"> {{ item.datetime  }} </div>

        <!-- 普通的对话消息 -->
        <div
          v-if="['3','4','5'].indexOf(item.type) == -1"
          class="row"
          :class="item.from_user_id == $store.state.uid ? 'right' : ''"
        >
          <!-- 头像展示 -->
        <router-link
          :to="{
            path: '/wechat/dialogue/dialogue-detail',
            query: { mid: mid },
          }"
        >
        <img :src="item.from_user_headimg" class="header" />
        </router-link>
          
          <div class="msg-box">
            <!-- 右侧展示 -->
            <span v-if="item.from_user_id == $store.state.uid">
              <!-- {{ item.create_time | fmtDate("Y-MM-dd hh:mm") }} -->
              <span v-if="midInfo.type == 2">{{
                item.from_user_nickname
              }}</span></span
            >
            <!-- 左侧展示 -->
            <span v-else
              ><aaa v-if="midInfo.type == 2">{{ item.from_user_nickname }}</aaa>
              <!-- {{ item.create_time | fmtDate("Y-MM-dd hh:mm") }} -->
              </span>

            <!-- 文字展示 -->
            <p
              class="text"
              v-if="item.type == 1"
              v-more
              v-html="parsingEmoji(item.msg)"
            ></p>

            <!-- 图片展示 -->
            <div v-if="item.type == 2" class="msg-image-box">
              <img :src="item.msg" alt="" @click="lookImage(item.msg)"/>
            </div>

            <!-- 名片展示 -->
            
            <div v-if="item.type == 6 || item.type==7" class="msg-image-box card-box">
              <msgCard :msg="item.msg" :type="item.type" :key="'card_'+index"></msgCard>
            </div>

          </div>
        </div>
        <!-- 普通对话消息结束 -->

        <!-- 系统提示 -->
        <div class="system-msg" v-if="item.type == 3">
          <!-- 自己的系统提示 -->
          <span v-if="item.from_user_id == $store.state.uid">你</span>
          <!-- 别人发送的系统提示 -->
          <span v-else>{{ item.from_user_nickname }}</span>
          {{ item.msg }}
        </div>

        <!-- 系统提示2 -->
        <div class="system-msg" v-if="item.type == 5">
          {{ item.msg }}
        </div>

        <!-- 仅自己和对方可见的系统提示 -->
        <div
          class="system-msg"
          v-if="item.type == 4 && item.from_user_id == $store.state.uid"
        >
          <!-- 自己的系统提示 -->
          <!-- <span v-if="item.from_user_id == $store.state.uid">你</span> -->
          <!-- 别人发送的系统提示 -->
          <span>"{{ item.from_user_nickname }}"</span>
          {{ item.msg }}
        </div>
      </div>

      <!-- 消息列表结束 -->
      <div style="height: 50px">&nbsp;</div>

      <span class="msg-more" id="msg-more">
        <ul>
          <li>复制</li>
          <li>转发</li>
          <li>撤回</li>
          <li>删除</li>
        </ul>
      </span>
    </section>

    <!-- 长按语音事件 -->
    <footer class="dialogue-footer" :class="dialogueFooterClass">
      <div class="component-dialogue-bar-person">
        
        <!-- 发送语音的图标 -->
        <!-- <span
          class="iconfont icon-dialogue-jianpan"
          v-show="!currentChatWay"
          v-on:click="currentChatWay = true"
        ></span>
        <span
          class="iconfont icon-dialogue-voice"
          v-show="currentChatWay"
          v-on:click="currentChatWay = false"
        ></span> -->
        <!-- 发送语音图标结束 -->

        <div class="chat-way" v-show="!currentChatWay">
          <!-- v-press -->
          <div class="chat-say" v-press>
            <span class="one">按住 说话</span>
            <span class="two">松开 结束</span>
          </div>
        </div>
        <div class="chat-way" v-show="currentChatWay">
          <input
            v-model="msgText"
            id="input"
            ref="input"
            class="chat-txt"
            type="text"
            v-on:focus="focusIpt"
            v-on:blur="blurIpt"
            @keyup.enter="sendMessage"
            @click="handleInputClick"
          />
          <!-- <div class="chat-txt" 
          ref="input"
          contenteditable=true 
          placeholder="请输入内容" 
          v-html="parsingEmoji(msgText)" 
          @input="handleInput"
          @click="handleInputClick"
           > </div> -->
        </div>
        <!-- 表情 -->
        <span
  
          class="expression iconfont icon-dialogue-smile"
          :class="showEmoji ? 'cgreen' : ''"
          @click="clickBtn('emoji')"
        ></span>
        <!-- 更多 加号 -->

        <span
          v-if="msgText == '' || !currentChatWay"
          class="more iconfont icon-dialogue-jia"
          :class="showJia ? 'cgreen' : ''"
          @click="clickBtn('jia')"
        ></span>

        <span v-else class=" expression more message-btn" @click="sendMessage">发送</span>

        <!-- 语音 取消 发送等 -->
        <div class="recording" style="display: none" id="recording">
          <div
            class="recording-voice"
            style="display: none"
            id="recording-voice"
          >
            <div class="voice-inner">
              <div class="voice-icon"></div>
              <div class="voice-volume">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
            <p>手指上划,取消发送</p>
          </div>
          <div class="recording-cancel" style="display: none">
            <div class="cancel-inner"></div>
            <p>松开手指,取消发送</p>
          </div>
        </div>
      </div>

      <!-- 底部更多功能 -->
      <div class="footer-more" v-if="showJia">
        <van-uploader :after-read="afterReadImage">
          <div class="footer-more-item">
            <van-icon name="photo-o" />
            <span>相册</span>
          </div>
        </van-uploader>

      <van-uploader :after-read="afterReadFile" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
          <div class="footer-more-item">
            <van-icon name="idcard" />
            <span>文件</span>
          </div>
      </van-uploader>

        <router-link
          :to="{
            path: '/contact/friend-list',
            query: { mid: mid,nickName:midNickName },
          }"
          tag="span"
        >
        <div class="footer-more-item">
         <van-icon name="contact" />
          <span>名片</span>
        </div>
        
        </router-link>



      </div>

      <!-- 表情 -->
      <div class="footer-more" v-if="showEmoji">
           <Emoji3 @chooseEmoji="chooseEmoji"></Emoji3>
        <!-- <Emoji @chooseEmoji="chooseEmoji" /> -->
      </div>

   
    </footer>
  </div>
</template>
<script>
import {
  ApiGetMessageList,
  ApiSendMessage,
  ApiSetUp,
  ApisetRead,
  ApiGetGroupInfo,
} from "@/api/api/message";
import { upFile, upImage, upImage2 } from "@/api/api/image";

import { Icon,Badge,ImagePreview  } from "vant";

// 引入表情
// import drawEmoji from "@/utils/emoji/emoji";

import { Uploader } from "vant";
import msgCard from './msg-card.vue'
import Emoji from "@/components/emoji2/emoji.vue";
import Emoji3 from "@/components/emoji3/index.vue";

import "@/components/emoji2/emjoymethod";
import "@/components/emoji2/emjoy.css";
// import message from '@/utils/message';
// import { ApiGetUserInfo } from '@/api/api/Client';
import { ApiGetDialogueList } from '@/api/api/main';

export default {
  data() {
    return {
      // pageName: this.$route.query.name,
      currentChatWay: true, //ture为键盘打字 false为语音输入
      timer: null,
      // sayActive: false // false 键盘打字 true 语音输入
      msgInfo: {},
      mid: 0,
      msgText: "", //即将发送的消息
      showJia: false, //是否显示更多功能
      showEmoji: false, //是否显示表情
      // emojiList: [],
      fileList: [], //文件列表

      page: 0, //页码
      scrollTop: 0, //滚动条高度
      loading: false, //是否加载中
      finished: false, //最后一页

      lastEditRange: null, //定于最后的光标对象


      midInfo:{},// 群聊信息
      _midInfo:{},//简洁的聊天对象数据（用于读取会话列表失败时，使用）

      history_url:'',//历史路由
    };
  },
  beforeRouteEnter(to, from, next) {
    
    next((vm) => {
      vm.history_url = from.fullPath
      // console.log(vm.history_url,from,'---vm.history_url')
      // vm.$store.commit("setPageName", vm.$route.query.name);
    });
  },
  mounted() {
    this.mid = this.$route.query.mid;
    this.init();
    //获取mid的基本信息
    this.getMidInfo();
    //初始化 回到最后一条记录
    this.toPageEnd();

    this.systemSetUp(); //将隐藏会话加入到会话列表
  },
  computed: {
    // 聊天消息记录
    msgList() {
      let mid = this.mid;
      let messageList = this.$store.state.messageList[mid] || [];
      if(messageList?.list?.length){
        let oldTime = false;
        let oldDatetime = ''
        // 设置聊天时间显示
        for(let i=0 ;i<messageList.list.length;i++){
          let item = messageList.list[i]
          //和上一个时间比较  每隔3分钟 显示一次时间
          let newTime = new Date(item.create_time).getTime()
          if(item.showTime==1){
            if(oldDatetime == item.datetime){
              //重复了
              item.showTime = 0// 隐藏后面的
            }else{
              oldTime = newTime
            }
            continue
          }
          if(!oldTime){
            oldTime = newTime
            item.showTime = 1
          }else{
            //俩个时间 相隔分钟数
            let minute = Math.ceil( Math.abs(newTime-oldTime)/1000 / 60)
            if(minute>3){
              item.showTime = 1
              oldTime = newTime
            }
            // console.log(oldTime,newTime,newTime-oldTime,(newTime-oldTime)/1000/60,minute,'--时间差')
          }
        }
      }


      return this.$store.state.messageList[mid] || [];
    },

    //当前的聊天对象名称
    midNickName() {
      let midInfo = this.midInfo;
      if (midInfo.type == 1) {
        return midInfo.remark ? midInfo.remark : midInfo.getClientMid.nickname;
      } else {
        return midInfo?.getUserGroup?.name || (this._midInfo?.getUserGroup?.name||'会话列表');
      }
    },
    //聊天对象人数
    midNumber() {
      let midInfo = this.midInfo;
      if (midInfo.type == 1) {
        return 1;
      } else {
        return midInfo?.getUserGroup?.member_number || (this._midInfo?.getUserGroup?.member_number || 0);
      }
    },
    //未读消息数
    msgNumberAll() {
      let number = 0;
      let newFriendNumber = this.$store.state.newFriendNumber
      for (var i in this.$store.state.msgList.baseMsg) {
        let item = this.$store.state.msgList.baseMsg[i];
        number += item.msg_reda_number;
      }
      return number+newFriendNumber;
    },
    //底部class
    dialogueFooterClass() {
      if (this.showJia) {
        return "show-more";
      } else if (this.showEmoji) {
        return "show-emoji";
      }
      return "";
    },
  },
  //方法集
  methods: {
    // 初始化获取聊天记录
    init() {
      // 创建监听滚动条事件
      document.getElementById("msg-list").addEventListener(
        "scroll",
        () => {
          this.scrollTop = document.getElementById("msg-list").scrollTop;
        },
        false
      );
      // 更新vuex 当前聊天对象
      this.$store.commit("setData", { key: "mid", value: this.mid });

      //手动获取群聊信息
      // this.getGroupInfo()
      
      //如果消息记录存在 则无需加载
      if (this.$store.state.messageList[this.mid]) {
        return false;
      }
      //消息记录
      let params = { mid: this.mid,isMidInfo:this.midInfo?.id||0 };
      ApiGetMessageList(params).then(({ data, msg }) => {
        this.$store.commit("setMessageList", {
          mid: this.mid,
          msgList: data.data,
          page: data.current_page,
        });
        this.toPageEnd();
      });
    },
    // 监听键盘事件
    hookResize(){
      var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
      window.onresize = function() {
          var nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
          if (clientHeight - nowClientHeight > 60 ) {//因为ios有自带的底部高度
              //键盘弹出的事件处理
              document.getElementById("apply").classList.add("focusState");
          }
          else {
              //键盘收起的事件处理
            document.getElementById("apply").classList.remove("focusState");
          } 
      };
    },
    //返回上一页
    returnBtn(){
        this.$router.replace({path:this.history_url})
    },
    //获取聊天对象的基本信息
    async getMidInfo(){
      let wxid = this.mid;
      let { baseMsg } = this.$store.state.msgList;
      let info = {};
      for (let i in baseMsg) {
        if (baseMsg[i].mid == wxid) {
          info = baseMsg[i];
          break;
        }
      }
      // 会话列表不存在  就自动获取对方信息
      if(!info?.id){
        let params = {mid:this.mid}
        let res =await ApiGetDialogueList(params)
        info = res.data[0]
        info.is_show = 1;//在会话列表显示
        this.$store.commit('addMsgList',info)
      }
      this.midInfo = info
    },
    //如果是隐藏的会话列表  则释放出来
    systemSetUp() {
      for (let i in this.$store.state.msgList.baseMsg) {
        let item = this.$store.state.msgList.baseMsg[i];
        if (item.mid == this.mid) {
          // 如果在会话列表隐藏了 那么就将其展示出来
          if (item.is_show == 0) {
            item.is_show = 1;
            let params = {
              mid: this.mid,
              field: "is_show",
              value: 1,
            };
            //加入会话列表
            ApiSetUp(params).then(({ msg }) => {});
          }
          return;
        }
      }
    },
    //获取更多的页数
    getMessageList() {
      //已经加载结束  无需加载
      if (this.finished) return;
      //进入加载中 防止重复加载
      if (this.loading) return;
      this.loading = true;

      let page = this.msgList.page;
      //消息记录
      let params = { mid: this.mid, page: page + 1, pageSize: 2 };
      ApiGetMessageList(params).then(({ data, msg }) => {
        // 恢复加载状态
        this.loading = false;
        //加载完成
        if (data.current_page >= data.last_page) {
          this.finished = true;
        }
        let oldScrollTop = document.getElementById("msg-list").scrollHeight;
        document.getElementById("msg-list").style.overflowY = "hidden";
        this.$store.commit("pushMessageInfo", {
          mid: this.mid,
          msgList: data.data,
          page: data.current_page,
        });
        this.toPageEnd(oldScrollTop);
      });
    },
    //界面拉到页尾
    toPageEnd(scrollTop) {
      setTimeout(() => {
        document.getElementById("msg-list").style.overflowY = "auto";
        let scrollHeight = document.getElementById("msg-list").scrollHeight;
        if (scrollTop) {
          scrollHeight = scrollHeight - scrollTop;
        }
        document.getElementById("msg-list").scrollTop = scrollHeight;
      }, 1);
    },
    //发送文字消息
    sendMessage() {
      this.clickBtn();
      // console.log(123,'--发送事件')
      //发送文本消息
      this._sendMessage(this.msgText, 1);
    },
    //上传图片 成功
    afterReadImage(file) {
      let param = new FormData();
      param.append("file", file.file);
      param.append("name", file.name);
      upImage(param).then(({ data, msg }) => {
        //  发送图片消息
        this.showJia = false;
        this._sendMessage(data.file, 2);
      });
    },
    //上传文件
    afterReadFile(file){
      let param = new FormData();
      param.append("file", file.file);
      param.append("name", file.name);
      upFile(param).then(({ data }) => {
        //  发送文件消息
        this.showJia = false;
        let msg = JSON.stringify(data.data)
        this._sendMessage(msg, 7);
      });
    },
    lookImage(image){
      ImagePreview([image])
    },

    // 给当前的人发送消息
    _sendMessage(msg, type) {
      let params = {
        mid: this.mid,
        msg: msg,
        type: type || 1,
      };
      ApiSendMessage(params).then(({ data, msg }) => {
        this.msgText = ""; //清除消息框
        //发送消息成功 客户端给视图追加消息
        this.$store.commit("addMessageList", {
          mid: this.mid,
          msgList: data,
        });

        // 滚动条 到底部
        // document.documentElement.scrollTop = 9999;
        setTimeout(() => {
          // console.log(document.getElementById('msg-list').scrollTop,'---document.documentElement')
          document.getElementById("msg-list").scrollTop =
            document.getElementById("msg-list").scrollHeight;
          // document.getElementById('msg-list').scrollTop = document.getElementById('myData').scrollHeight;
        }, 10);
      });
    },

    // 解决输入法被激活时 底部输入框被遮住问题
    focusIpt() {
      this.clickBtn();// 关闭表情选项
      this.timer = setInterval(function () {
        document.body.scrollTop = document.body.scrollHeight;
        console.log( document.body.scrollTop,'---focusIpt')
      }, 100);
    },
    // 失去焦点
    blurIpt() {
      clearInterval(this.timer);
      this.handleInputClick(); //重新记录焦点位置
    },
    // 点击空白区域，菜单被隐藏
    MenuOutsideClick(e) {
      var container = document.querySelectorAll(".text"),
        msgMore = document.getElementById("msg-more");
      if (e.target.className !== "text") {
        msgMore.style.display = "none";
        container.forEach((item) => (item.style.backgroundColor = "#fff"));
      }
      //隐藏表情 文件框
      this.clickBtn();
    },
    //点击按钮
    clickBtn(type) {
      if (type == "jia") {
        this.showEmoji = false;
        this.showJia = !this.showJia;
      } else if (type == "emoji") {
        this.showEmoji = !this.showEmoji;
        this.showJia = false;
      } else {
        this.showEmoji = false;
        this.showJia = false;
      }
    },
    // 选择了表情
    chooseEmoji(Text) {
      // 对光标位置 插入
      this.msgText =
        this.msgText.slice(0, this.lastEditRange) +
        Text +
        this.msgText.slice(this.lastEditRange);
      this.lastEditRange += Text.length;
    },
    // 记录光标位置
    handleInputClick() {
      let position = document.getElementById("input");
      let CaretPos = 0;
      if (position.selectionStart || position.selectionStart == "0") {
        // Firefox support
        CaretPos = position.selectionStart;
      }
      // 记录 lastEditRange 光标位置
      this.lastEditRange = CaretPos;
    },
  },
  watch: {
    scrollTop(val) {
      // console.log(this.scrollTop,this.loading , this.finished)
      //如果是加载中 或者加载完毕 就不再执行
      if (this.loading || this.finished) {
        return;
      }
      if (this.scrollTop < 10) {
        //加载下一页
        this.getMessageList();
      }
    },
    //监听个人信息
    midInfo(val) {
      //如果有未读消息数 修改为已读
      // console.log(val.msg_reda_number, "---未读消息数量");
      if (val.msg_reda_number > 0) {
        let params = { mid: this.mid };
        ApisetRead(params).then((res) => {
          val.msg_reda_number = 0; // 更新视图
        });
      }
    },
  },
  components: {
    [Icon.name]: Icon,
    [Badge.name]: Badge,
    [Uploader.name]: Uploader,
    Emoji, 
    msgCard,
    Emoji3,
  },
  // 指令
  directives: {
    // 长按说话动画
    press: {
      inserted(element) {
        var recording = document.querySelector(".recording"),
          recordingVoice = document.querySelector(".recording-voice"),
          recordingCancel = document.querySelector(".recording-cancel"),
          // startTx,
          startTy;
        //监听手指长按事件
        element.addEventListener(
          "touchstart",
          function (e) {
            // 用bind时，vue还没插入到dom,故dom获取为 undefine，用 inserted 代替 bind,也可以开个0秒的定时器
            element.className = "chat-say say-active";
            recording.style.display = recordingVoice.style.display = "block";
            var touches = e.touches[0];
            // startTx = touches.clientX
            startTy = touches.clientY;
            e.preventDefault();
          },
          false
        );
        element.addEventListener(
          "touchend",
          function (e) {
            /*var touches = e.changedTouches[0];
                        var distanceY = startTy - touches.clientY;
                        if (distanceY > 50) {
                            console.log("取消发送信息");
                        }else{
                            console.log("发送信息");
                        }*/

            element.className = "chat-say";
            recordingCancel.style.display =
              recording.style.display =
              recordingVoice.style.display =
                "none";
            e.preventDefault();
          },
          false
        );
        element.addEventListener(
          "touchmove",
          function (e) {
            var touches = e.changedTouches[0],
              // endTx = touches.clientX,
              endTy = touches.clientY,
              // distanceX = startTx - endTx,
              distanceY = startTy - endTy;

            if (distanceY > 50) {
              element.className = "chat-say";
              recordingVoice.style.display = "none";
              recordingCancel.style.display = "block";
            } else {
              element.className = "chat-say say-active";
              recordingVoice.style.display = "block";
              recordingCancel.style.display = "none";
            }
            // 阻断事件冒泡 防止页面被一同向上滑动
            e.preventDefault();
          },
          false
        );
      },
    },
    // 增加长按撤回事件
    more: {
      bind(element) {
        var startTx, startTy;
        element.addEventListener(
          "touchstart",
          function (e) {
            var msgMore = document.getElementById("msg-more"),
              touches = e.touches[0];
            startTx = touches.clientX;
            startTy = touches.clientY;
            let scrollTop = document.getElementById("msg-list").scrollTop
            console.log(element,element.offsetTop,scrollTop,'--elelment')
          
            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
              // 控制菜单的位置
              msgMore.style.left =
                (startTx - 18 > 180 ? 180 : startTx - 18) + "px";
              msgMore.style.top = element.offsetTop - 33-scrollTop + "px";
              msgMore.style.display = "block";
              element.style.backgroundColor = "#e5e5e5";
            }, 500);
          },
          false
        );
        element.addEventListener(
          "touchmove",
          function (e) {
            var touches = e.changedTouches[0],
              disY = touches.clientY;
            if (Math.abs(disY - startTy) > 10) {
              clearTimeout(this.timer);
            }
          },
          false
        );
        element.addEventListener(
          "touchend",
          function () {
            clearTimeout(this.timer);
          },
          false
        );
      },
    },
  },
  destroyed() {
    // 移除vuex 当前聊天对象
    this.$store.commit("setData", { key: "mid", value: 0 });
  },
};
</script>
<style lang="less">
@import "../../assets/less/dialogue.less";

.say-active {
  background: #c6c7ca;
}
.system-msg {
  text-align: center;
  color: #999;
  margin: 20px 0px;
}
.cgreen {
  color: #058618 !important;
  font-size: 12px;
}

#wx-header .center .icon-return-arrow{
  display: flex;
  align-items: center;
}

.chat-way{
  margin-right: 5px;
}
</style>